#ifndef THREAD_CACHE_H_V3
#define THREAD_CACHE_H_V3

#include "Common.h"
using namespace std;

namespace memoryPoolV3 {
class ThreadCache {
public:
    // 每个线程一个实例
    static ThreadCache *getInstance() {
        static thread_local ThreadCache instance;
        return &instance;
    }

    void *allocate(size_t size);
    void deallocate(void *ptr, size_t size);

private:
    ThreadCache() {
        freeList_.fill(nullptr);
        freeListSize_.fill(0);
    }

    // 从中心缓存获取内存
    void *fetchFromCentralCache(size_t idx);

    size_t getBatchNum(size_t size);

    // 归还内存到中心缓存
    void returnToCentralCache(void *start, size_t size);

    bool shouldReturnToCentralCache(size_t idx);

private:
    // 各线程自由链表数组以及大小
    array<void *, FREE_LIST_SIZE> freeList_;
    array<size_t, FREE_LIST_SIZE> freeListSize_;
};
} // namespace memoryPoolV3

#endif